from flask import Blueprint, jsonify, request
from data.db.db_manager import DBManager


watchlist_bp = Blueprint('watchlist', __name__, url_prefix='/api/watchlist')
db_manager = DBManager()

@watchlist_bp.route('/list', methods=['GET'])
def get_watchlist():
    """获取用户的所有监视列表"""
    try:
        user_id = request.args.get('user_id', 1)  # 默认用户ID为1
        watchlists = db_manager.get_user_watchlists(user_id)
        return jsonify({"s": "ok", "data": watchlists})
    except Exception as e:
        return jsonify({"s": "error", "errmsg": str(e)})

@watchlist_bp.route('/save', methods=['POST'])
def save_watchlist():
    """保存或更新监视列表"""
    try:
        data = request.get_json()
        if not data or 'name' not in data:
            return jsonify({"s": "error", "errmsg": "Missing name field"})
        
        user_id = data.get('user_id', 1)  # 默认用户ID为1
        name = data['name']
        items = data.get('items')  # items是可选的
    
        result = db_manager.save_or_update_watchlist(user_id, name, items)
        return jsonify({
            "s": "ok",
            "data": result
        })
    except Exception as e:
        return jsonify({"s": "error", "errmsg": str(e)})

@watchlist_bp.route('/rename', methods=['POST'])
def rename_watchlist():
    """重命名监视列表"""
    try:
        data = request.get_json()
        if not data or 'old_name' not in data or 'new_name' not in data:
            return jsonify({"s": "error", "errmsg": "Missing old_name or new_name field"})
        
        user_id = data.get('user_id', 1)  # 默认用户ID为1
        old_name = data['old_name']
        new_name = data['new_name']
        
        db_manager.rename_watchlist(user_id, old_name, new_name)
        return jsonify({"s": "ok"})
    except ValueError as e:
        return jsonify({"s": "error", "errmsg": str(e)})
    except Exception as e:
        return jsonify({"s": "error", "errmsg": str(e)})

@watchlist_bp.route('/delete', methods=['DELETE'])
def delete_watchlist():
    """删除监视列表"""
    try:
        name = request.args.get('name')
        if not name:
            return jsonify({"s": "error", "errmsg": "Missing name parameter"})
        
        user_id = request.args.get('user_id', 1)  # 默认用户ID为1
        
        if db_manager.delete_watchlist_by_name(user_id, name):
            return jsonify({"s": "ok"})
        return jsonify({"s": "error", "errmsg": "Watchlist not found"})
    except Exception as e:
        return jsonify({"s": "error", "errmsg": str(e)})
